package cn.shujuhai.common.config;

import cn.shujuhai.common.service.RateLimitService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    @Autowired
    private RateLimitService rateLimitService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!rateLimitService.tryAcquire()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("请求过于频繁，请稍后再试");
            return false;
        }
        return true;
    }
}